package com.xiaoyi.config;



import com.xiaoyi.annotataion.Encrypt;
import com.xiaoyi.encrypt.EncryptorFactory;
import com.xiaoyi.encrypt.IEncryptorStrategy;
import com.xiaoyi.enums.AlgorithmEnum;
import com.xiaoyi.support.EncryptExecutor;

import java.util.Objects;


/**
  *
  * @author xiaoyi
  * @version 1.0.0
  * @date 2023/8/6 14:51
  */
public class DefaultEncryptionExecutor implements EncryptExecutor {


    private EncryptionConfig encryptionConfig;


    @Override
    public String encryptParameter(String paramName, String paramValue, Encrypt annotation) {
        if (!encryptionConfig.getEnable()) {
            return paramValue;
        }
        if (!encryptionConfig.getEnableEncrypt()) {
            return paramValue;
        }

        IEncryptorStrategy encryptor = EncryptorFactory.createEncryptor(chooseAlgorithm(annotation));

        return encryptor.encrypt(paramValue,encryptionConfig,annotation);
    }

    @Override
    public String encryptField(String fieldName, String fieldValue, Encrypt annotation, Object pojo) {
        if (!encryptionConfig.getEnable()) {
            return fieldValue;
        }
        if (!encryptionConfig.getEnableEncrypt()) {
            return fieldValue;
        }
        IEncryptorStrategy encryptor = EncryptorFactory.createEncryptor(chooseAlgorithm(annotation));

        return encryptor.encrypt(fieldValue,encryptionConfig,annotation);
    }

    @Override
    public String decryptField(String fieldName, String fieldValue, Encrypt annotation, Object pojo) {
        if (!encryptionConfig.getEnable()) {
            return fieldValue;
        }
        if (!encryptionConfig.getEnableDecrypt()) {
            return fieldValue;
        }
        IEncryptorStrategy encryptor = EncryptorFactory.createEncryptor(chooseAlgorithm(annotation));
        return encryptor.decrypt(fieldValue,encryptionConfig,annotation);
    }
    public void setEncryptionConfig(EncryptionConfig encryptionConfig) {
        this.encryptionConfig = encryptionConfig;
    }
    private AlgorithmEnum chooseAlgorithm(Encrypt encrypt){

        AlgorithmEnum algorithm = encryptionConfig.getAlgorithm();
        // 全局没有配置
        if (Objects.isNull(algorithm)){
            return encrypt.algorithm();
        }else{
        // 全局配置了
            // 一样的话，返回谁的都行
            if (encrypt.algorithm().getValue().equals(algorithm.getValue())){
                return encrypt.algorithm();
            }
            if (AlgorithmEnum.DEFAULT.getValue().equals(encrypt.algorithm().getValue())){
                // 局部是默认的，就返回全局的
                return algorithm;
            }else{
                // 不是默认的就，就返回注解的
                return encrypt.algorithm();
            }
        }
    }



}